import { IPSAppCodeList, IPSAppViewLogic } from '@ibiz/dynamic-model-api';
import { IAppMDCtrlController, IParam, IUIDataParam, MobContextMenuEvents, MobToolbarEvents } from '../../../interface';
import { AppCtrlControllerBase } from './app-ctrl-controller-base';
import { AppViewLogicUtil } from '../../utils';

export class AppMDCtrlController extends AppCtrlControllerBase implements IAppMDCtrlController {
  /**
   * @description 部件行为--fetch
   * @type {string}
   * @memberof AppMDCtrlController
   */
  public fetchAction?: string;

  /**
   * @description 多数据部件数据集合
   * @type {IParam[]}
   * @memberof AppMDCtrlController
   */
  public items: IParam[] = [];

  /**
   * @description 当前页
   * @type {number}
   * @memberof AppMDCtrlController
   */
  public curPage: number = 1;

  /**
   * @description 是否支持分页
   * @type {boolean}
   * @memberof AppMDCtrlController
   */
  public isEnablePagingBar: boolean = true;

  /**
   * @description 排序对象
   * @type {IParam}
   * @memberof AppMDCtrlController
   */
  public sort: IParam = {};

  /**
   * @description 是否禁用排序
   * @type {boolean}
   * @memberof AppMDCtrlController
   */
  public isNoSort: boolean = false;

  /**
   * @description 排序方向
   * @type {string}
   * @memberof AppMDCtrlController
   */
  public minorSortDir: string = '';

  /**
   * @description 排序属性
   * @type {string}
   * @memberof AppMDCtrlController
   */
  public minorSortPSDEF: string = '';

  /**
   * @description 分页条数
   * @type {number}
   * @memberof AppMDCtrlController
   */
  public limit: number = 20;

  /**
   * @description 总条数
   * @type {number}
   * @memberof AppMDCtrlController
   */
  public totalRecord: number = 0;

  /**
   * @description 是否默认选中第一条数据
   * @type {boolean}
   * @memberof AppMDCtrlController
   */
  public isSelectFirstDefault: boolean = false;

  /**
   * @description 是否开启分组
   * @type {boolean}
   * @memberof AppMDCtrlController
   */
  public isEnableGroup: boolean = false;

  /**
   * @description 代码表分组集合
   * @type {IParam[]}
   * @memberof AppMDCtrlController
   */
  public groupDetail: IParam[] = [];

  /**
   * @description 分组模式
   * @type {('AUTO' | 'CODELIST' | null)}
   * @memberof AppMDCtrlController
   */
  public groupMode: 'AUTO' | 'CODELIST' | null = null;

  /**
   * @description 分组属性
   * @type {string}
   * @memberof AppMDCtrlController
   */
  public groupField: string = '';

  /**
   * @description 分组数据
   * @type {*}
   * @memberof AppMDCtrlController
   */
  public groupData: IParam[] = [];

  /**
   * @description 是否多选
   * @type {boolean}
   * @memberof AppMDCtrlController
   */
  public isMultiple: boolean = false;

  /**
   * @description 选中数组
   * @type {Array<any>}
   * @memberof AppMDCtrlController
   */
  public selections: IParam[] = [];

  /**
   * @description 数据映射（用于将列表项相关信息传递给面板）
   * @type {Map<string, IParam>}
   * @memberof AppMDCtrlController
   */
  public dataMap: Map<string, IParam> = new Map();

  /**
   * @description 获取单项数据
   * @return {*}  {IParam}
   * @memberof AppMDCtrlController
   */
  public getData(): IParam {
    return this.selections[0];
  }

  /**
   * @description 获取多项数据
   * @return {*}  {IParam[]}
   * @memberof AppMDCtrlController
   */
  public getDatas(): IParam[] {
    return this.selections;
  }

  /**
   * @description 初始化输入数据
   * @param {*} opts 输入参数
   * @memberof AppMDCtrlController
   */
  public initInputData(opts: any) {
    super.initInputData(opts);
    this.isMultiple = opts.isMultiple;
  }

  /**
   * @description 部件基础数据初始化
   * @memberof AppMDCtrlController
   */
  public ctrlBasicInit() {
    super.ctrlBasicInit();
    this.initGroupOptions();
    this.initSort();
    this.initSelects();
    this.initDataMap();
    this.limit = this.controlInstance.pagingSize != 1000 ? this.controlInstance.pagingSize : 20;
    if (App.isPreviewMode()) {
      this.items = this.previewData;
    }
  }

  /**
   * @description 数据映射
   * @memberof AppMDCtrlController
   */
  public initDataMap() {}

  /**
   * @description 初始化实体行为
   * @memberof AppMDCtrlController
   */
  public initActions() {
    super.initActions();
    this.fetchAction = this.controlInstance.getFetchPSControlAction?.()?.actionName || 'FetchDefault';
  }

  /**
   * @description 初始化选中值
   * @memberof AppMDCtrlController
   */
  private initSelects() {
    if (this.viewParam?.selectedData) {
      this.selections = this.viewParam.selectedData;
    }
  }

  /**
   * @description 初始化分组配置
   * @private
   * @memberof AppMDCtrlController
   */
  private initGroupOptions() {
    this.isEnableGroup = this.controlInstance?.enableGroup;
    if (this.isEnableGroup) {
      this.groupMode = this.controlInstance.groupMode;
      const groupField = this.controlInstance.getGroupPSAppDEField?.()?.codeName;
      if (groupField) {
        this.groupField = groupField.toLowerCase() as string;
      }
    }
  }

  /**
   * @description 初始化排序
   * @private
   * @memberof AppMDCtrlController
   */
  private initSort() {
    this.isNoSort = this.controlInstance.noSort;
    this.minorSortDir = this.controlInstance.minorSortDir;
    this.minorSortPSDEF = this.controlInstance.getMinorSortPSAppDEField?.()?.codeName?.toLowerCase();
    this.sort = { sort: '' };
    if (this.minorSortPSDEF) {
      Object.assign(this.sort, {
        sort: `${this.minorSortPSDEF},${this.minorSortDir ? this.minorSortDir : 'ASC'}`,
      });
    }
  }

  /**
   * @description 多数据部件模型加载
   * @memberof AppMDCtrlController
   */
  public async ctrlModelLoad() {
    await super.ctrlModelLoad();
    await this.initGroupDetail();
  }

  /**
   * @description 初始化代码表分组集合
   * @memberof AppMDCtrlController
   */
  private async initGroupDetail() {
    const groupCodeList = this.controlInstance.getGroupPSCodeList?.() as IPSAppCodeList;
    if (this.isEnableGroup && groupCodeList) {
      await groupCodeList.fill?.();
      const codeListItems = await App.getCodeListService().getDataItems({
        tag: groupCodeList.codeName,
        type: groupCodeList.codeListType,
        navContext: this.context,
        navViewParam: this.viewParam,
      });
      if (codeListItems && codeListItems.length) {
        codeListItems.forEach((item: any) => {
          if (item.value && item.text) {
            this.groupDetail.push({
              value: item.value,
              text: item.text,
            });
          }
        });
      }
    }
  }

  /**
   * @description 获取分组数据
   * @memberof AppMDCtrlController
   */
  protected getGroupData() {
    if (
      this.getGroupDataByCodeList &&
      this.getGroupDataByCodeList instanceof Function &&
      Object.is(this.groupMode, 'CODELIST')
    ) {
      this.getGroupDataByCodeList(this.items);
    } else if (
      this.getGroupDataAuto &&
      this.getGroupDataAuto instanceof Function &&
      Object.is(this.groupMode, 'AUTO')
    ) {
      this.getGroupDataAuto(this.items);
    }
  }

  /**
   * @description 获取代码表分组数据
   * @param {*} items 多数据部件数据
   * @memberof AppMDCtrlController
   */
  private getGroupDataByCodeList(items: any) {
    const group: Array<any> = [];
    this.groupDetail.forEach((obj: any, index: number) => {
      const data: any = [];
      items.forEach((item: any, i: number) => {
        if (item[this.groupField] === obj.value) {
          data.push(item);
        }
      });
      group.push(data);
    });
    group.forEach((arr: any, index: number) => {
      Object.assign(this.groupData[index], {
        text: this.groupDetail[index].text,
        items: arr,
      });
    });
    this.groupData.forEach((item: any, i: number) => {
      if (item.items.length == 0) {
        this.groupData.splice(i, 1);
      }
    });
  }

  /**
   * @description 获取自动分组数据
   * @param {*} items 多数据部件数据
   * @memberof AppMDCtrlController
   */
  private getGroupDataAuto(items: any) {
    let groups: Array<any> = [];
    items.forEach((item: any) => {
      if (item.hasOwnProperty(this.groupField)) {
        groups.push(item[this.groupField]);
      }
    });
    groups = [...new Set(groups)];
    groups.forEach((group: any, index: number) => {
      this.groupData[index] = {};
      this.groupData[index].items = [];
      items.forEach((item: any, i: number) => {
        if (group == item[this.groupField]) {
          this.groupData[index].text = group;
          this.groupData[index].items.push(item);
        }
      });
    });
  }

  /**
   * @description 选中数据改变
   * @param {any[]} selections 选中数组
   * @memberof AppMDCtrlController
   */
  selectionChange(selections: any[]): void {
    throw new Error('Method not implemented.');
  }

  /**
   * @description 项选中
   * @param {IParam} item 项数据
   * @param {MouseEvent} [event] 数据源
   * @memberof AppMDCtrlController
   */
  onRowSelect(item: IParam, event?: MouseEvent): void {
    throw new Error('Method not implemented.');
  }

  /**
   * @description 处理部件事件
   * @param {string} controlname 部件名
   * @param {string} action 部件行为
   * @param {*} data 行为触发数据
   * @memberof AppMDCtrlController
   */
  public handleCtrlEvent(controlname: string, action: string, data: IParam) {
    super.handleCtrlEvent(controlname, action, data);
    if (Object.is('contextmenu', controlname)) {
      this.handleContextMenuEvent(action, data);
    }
    if (Object.is(`${this.controlInstance.name}_quicktoolbar`, controlname) || Object.is(`${this.controlInstance.name}_batchtoolbar`, controlname)) {
      this.handleToolbarEvent(action, data);
    }
  }

  /**
   * @description 处理上下文菜单部件事件
   * @param {string} action 行为名
   * @param {IParam} data 行为数据
   * @memberof AppMDCtrlController
   */
  public handleContextMenuEvent(action: string, data: IParam) {
    switch (action) {
      case MobContextMenuEvents.MENUITEM_CLICK:
        this.handleContextMenuClick(data.name, data.data, data.event, data.detail);
        break;
    }
  }

  /**
   * @description 处理工具栏点击事件
   * @param {string} action 行为名
   * @param {IParam} data 行为数据
   * @memberof AppMDCtrlController
   */
  public handleToolbarEvent(action: string, data: IParam) {
    switch (action) {
      case MobToolbarEvents.TOOLBAR_CLICK:
        this.handleToolbarClick(data);
        break;
    }
  }

  /**
   * @description 处理上下文菜单点击事件
   * @param {string} name 上下文菜单部件名
   * @param {IParam} data 行为数据
   * @param {MouseEvent} event 行为事件源
   * @param {IParam} detail 行为模型
   * @memberof AppMDCtrlController
   */
  public handleContextMenuClick(name: string, data: IParam, event: MouseEvent, detail: IParam) {
    const getPSAppViewLogics = this.controlInstance.getPSAppViewLogics();
    const UIDataParam: IUIDataParam = this.getUIDataParam();
    Object.assign(UIDataParam, { data: data, event: event });
    AppViewLogicUtil.executeViewLogic(
      `${name}_${detail.name}_click`,
      UIDataParam,
      this.getUIEnvironmentParam(),
      this.viewCtx,
      getPSAppViewLogics,
    );
  }

  /**
   * @description 处理工具栏点击行为
   * @param {IParam} data 行为数据
   * @memberof AppMDCtrlController
   */
  public handleToolbarClick(data: IParam) {
    const appViewLogic: IPSAppViewLogic | null = this.controlInstance.findPSAppViewLogic(data.tag);
    const UIDataParam: IUIDataParam = this.getUIDataParam();
    Object.assign(UIDataParam, { event: data.event });
    AppViewLogicUtil.executeViewLogic(appViewLogic, UIDataParam, this.getUIEnvironmentParam(), this.viewCtx);
  }
}
